package com.sszh.base.utils;

import lombok.extern.log4j.Log4j;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Service;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

/**
 * @author WangJianGuo
 * @Title: HttpUtils
 * @Package com.sszh.base.utils
 * @Description: HTTP请求工具类
 * @date 2018-7-31 9:08
 */
@Service
@Log4j
@ComponentScan
public class HttpUtils {

    public String sendPost(String strURL) {

        URL url;
        String responseString = null;
        try {
            url = new URL(strURL);
            HttpURLConnection httpConn = (HttpURLConnection)
                    url.openConnection();

            httpConn.setRequestMethod("POST");
            httpConn.setConnectTimeout(TIME_OUT);
            httpConn.setReadTimeout(TIME_OUT);
            httpConn.connect();

            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    httpConn.getInputStream()));

            String line;
            StringBuffer buffer = new StringBuffer();

            while ((line = reader.readLine()) != null) {

                buffer.append(line);
            }

            reader.close();
            httpConn.disconnect();
            responseString = buffer.toString();

        } catch (Exception e) {
            e.printStackTrace();
        }

        return responseString;
    }

    /**
     * 超时时间
     */
    private static final int TIME_OUT = 8 * 1000;
    /**
     * 编码格式
     */
    private static final String CHARSET = "utf-8";
    /**
     * 前缀
     */
    private static final String PREFIX = "--";
    /**
     * 边界标识
     */
    private static final String BOUNDARY = "******";


    /**
     * 上传文件带参数
     * @param strParams
     * @param fileParams
     */
    public String postRequest(Map<String, String> strParams, Map<String, File[]> fileParams, String updateIp) {
        HttpURLConnection conn = null;
        try {
            String strUrl = updateIp+"/sszh/pzspt/realTimeUploadAlarm";
            URL url = new URL(strUrl);
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setReadTimeout(TIME_OUT);
            conn.setConnectTimeout(TIME_OUT);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            //Post 请求不能使用缓存
            conn.setUseCaches(false);
            // 设置header
            conn.setRequestProperty("Accept", "*/*");
            conn.setRequestProperty("Connection", "keep-alive");
            conn.setRequestProperty("Content-Type",
                    "multipart/form-data; boundary=" + BOUNDARY);
            /**
             * 请求体
             */

            //上传参数
            OutputStream dos = new DataOutputStream(conn.getOutputStream());
            //getStrParams()为一个
            log.info(getStrParams(strParams).toString());
            String paramData = getStrParams(strParams).toString();
            paramData = new String(paramData.getBytes(), "utf-8");
            dos.write(paramData.getBytes("utf-8"));
            dos.flush();

            //文件上传

            for (Map.Entry<String, File[]> fileEntry : fileParams.entrySet()) {
                for(int i = 0; i < fileEntry.getValue().length; i++) {
                    StringBuilder fileSb = new StringBuilder();
                    fileSb.append(PREFIX)
                            .append(BOUNDARY)
                            .append("\r\n")
                            .append("Content-Disposition: form-data; name=\"images\"; filename=\""
                                    + fileEntry.getValue()[i].getName() + "\"\r\n")
                            //此处的ContentType不同于 请求头 中Content-Type
                            .append("Content-Type: image/jpeg" + "\r\n")
                            .append("Content-Transfer-Encoding: 8bit" + "\r\n")
                            // 参数头设置完以后需要两个换行，然后才是参数内容
                            .append("\r\n");
                    dos.write(fileSb.toString().getBytes());
                    dos.flush();
                    if(fileEntry.getValue()[i].exists()) {
                        FileInputStream is = new FileInputStream(fileEntry.getValue()[i]);

                    DataInputStream inputStreams = new DataInputStream(is);

                    byte[] buffer = new byte[1024];
                    int bytes = 0;
                    while ((bytes = inputStreams.read(buffer)) != -1) {
                        dos.write(buffer, 0, bytes);
                    }
                    is.close();
                    inputStreams.close();
                    dos.write("\r\n".getBytes());
                    }else {
                        log.info("当前上传的图片不存在");
                        continue;
                    }
                }
            }
            //请求结束标志
            dos.write((PREFIX + BOUNDARY + PREFIX + "\r\n").getBytes());
            dos.flush();
            dos.close();
            //读取服务器返回信息
            if (conn.getResponseCode() == Constant.RESPONSE_CODE_200) {
                InputStream in = conn.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                String line = null;
                StringBuilder response = new StringBuilder();
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                return response.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }
        return "fail";
    }

    /**
     * 对post参数进行编码处理
     * @param strParams
     * @return
     */
    private static StringBuilder getStrParams(Map<String, String> strParams) {
        StringBuilder strSb = new StringBuilder();
        for (Map.Entry<String, String> entry : strParams.entrySet()) {
            strSb.append(PREFIX)
                    .append(BOUNDARY)
                    .append("\r\n")
                    .append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"" + "\r\n")
                    .append("Content-Type: text/plain; charset=" + CHARSET + "\r\n")
                    .append("Content-Transfer-Encoding: 8bit" + "\r\n")
                    // 参数头设置完以后需要两个换行，然后才是参数内容
                    .append("\r\n")
                    .append(entry.getValue())
                    .append("\r\n");
        }
        return strSb;
    }

}
